<template>
  <div class="app-container">
    <div class="filter-container">
      <p style="float:left;margin-top:5px;margin-left:2%">分类名称：</p>
      <el-input v-model="listQuery.name" size="small" placeholder="请输入分类名称" style="width: 150px;float:left" class="filter-item"
        @keyup.enter.native="handleFilter" />

      <el-button size="small" class="filter-item" type="success" icon="el-icon-search" style="margin-left:3%" @click="handleFilter">
        搜索
      </el-button>
      <el-button size="small" class="filter-item" style="margin-left: 10px;float:right" type="primary" icon="el-icon-edit"
        @click="handleCreate">添加</el-button>
    </div>

    <el-table v-loading="listLoading" :key="tableKey" :data="list" size="small" border fit highlight-current-row style="width: 100%;margin-top:1%"
      @selection-change="handleSelectionChange">
      <el-table-column label="ID" width="100px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="分类名称" width="200px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="父类名称" width="200px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.parentName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="图片" min-width="200px" align="center">
        <template slot-scope="scope">
          <img :src="scope.row.imgUrl" style="width:100px;height:100px" alt="">
        </template>
      </el-table-column>
      <el-table-column label="状态" width="150px" align="center">
        <template slot-scope="{ row }">
          <span>{{
            row.status == 0
              ? "正常"
              : row.status == 1
                ? "下架"
                  : "错误"
          }}</span>
          <!-- <span v-else>0</span> -->
        </template>
      </el-table-column>
      <el-table-column label="排序" width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.sortOrder }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="450px" class-name="small-padding fixed-width">
        <template slot-scope="{ row }">
          <el-button size="small" align="center" type="primary" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="small" align="center" type="danger" @click="handledelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize"
      @pagination="getList" />

    <el-dialog :close-on-click-modal="false" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible"
      append-to-body>
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="150px" style="width: 400px; margin-left:50px;">
        <el-form-item label="父类选择：">
          <el-select v-model="temp.parentName" @change="originNameChange" size="small" placeholder="全部" class="filter-item"
            style="width: 130px">
            <el-option v-for="item in originList" :key="item.id" :label="item.name" :value="item" />
          </el-select>
        </el-form-item>

        <el-form-item label="分类名称：">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="排序：">
          <el-input v-model="temp.sortOrder" />
        </el-form-item>
        <el-form-item label="状态：">
          <el-select v-model="temp.status" @change="statusChange" size="small" placeholder="全部" class="filter-item"
            style="width: 130px">
            <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
          </el-select>
        </el-form-item>

        <el-form-item label="添加图片：">
          <el-upload class="avatar-uploader" action="#" v-loading="dialogLoading" :show-file-list="false"
            :http-request="addImg">
            <img v-if="formImgUrl" :src="formImgUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          返回
        </el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    updateManu,
    manufacturerList,
    delManufacturer,
    createManufacturer,
    batchDel
  } from '@/api/manufacturer' // 异步请求 delLly

  import {
    getSecondListPage,
    createProCat,
    deleteProCat,
    getCatListOrigin
  } from '@/api/purchase/proCatReq'
  import {
    deleteFile,
    uploadFile
  } from '@/api/publicReq'
  import {
    parseTime
  } from '@/utils'
  import Pagination from '@/components/Pagination' // 分页插件

  const calendarTypeOptions = [{
      key: '0',
      display_name: '正常'
    },
    {
      key: '1',
      display_name: '下架'
    }
  ]
  const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name
    return acc
  }, {})

  export default {
    components: {
      Pagination
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          published: 'success',
          draft: 'info',
          deleted: 'danger'
        }
        return statusMap[status]
      },
      typeFilter(type) {
        return calendarTypeKeyValue[type]
      }
    },
    data() {
      return {
        statusData: '',
        dateValue: [],
        originList: [],
        tableKey: 0,
        list: null,
        total: 0,
        listLoading: true,
        listQuery: {
          pageNum: 1,
          pageSize: 10,
          phoneNumber: '',
          name: '',
          sort: '+id'
        },
        formImgUrl: "",
        deps: [],
        calendarTypeOptions,
        sortOptions: [{
          label: 'ID Ascending',
          key: '+id'
        }, {
          label: 'ID Descending',
          key: '-id'
        }],
        statusOptions: ['published', 'draft', 'deleted'],
        showReviewer: false,
        temp: {
          id: undefined,
          status:''
        },
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '修改',
          create: '添加'
        },
        rowId: "",
        dialogPvVisible: false,
        outerVisible: false,
        pvData: [],
        rules: {
          type: [{
            required: true,
            message: 'type is required',
            trigger: 'change'
          }],
          timestamp: [{
            type: 'date',
            required: true,
            message: 'timestamp is required',
            trigger: 'change'
          }],
          title: [{
            required: true,
            message: 'title is required',
            trigger: 'blur'
          }]
        },
        downloadLoading: false,
        liaUser: null,
        ids: [],
        select: null
      }
    },
    created() {
      this.getList()
    },
    methods: {
      handleSelectionChange(val) {
        val.forEach((item) => {
          this.select = item.id
        })
        this.ids.push(this.select)
      },

      // 获取list
      getList() {
        this.listLoading = true
        var params = {
          // pageConvert: true,
          pageNum: this.listQuery.pageNum,
          pageSize: this.listQuery.pageSize,
          name:this.listQuery.name,
          // phoneNumber:this.listQuery.phoneNumber
          draw: '1'
        }

        getSecondListPage(params).then(response => {
          this.list = response.data
          console.log(response)
          this.total = response.recordsTotal
          console.log(this.total)
          // Just to simulate the time of the request
          setTimeout(() => {
            this.listLoading = false
          }, 1.5 * 1000)
        })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      handleModifyStatus(row, status) {
        this.$message({
          message: '操作Success',
          type: 'success'
        })
        row.status = status
      },
      sortChange(data) {
        const {
          prop,
          order
        } = data
        if (prop === 'id') {
          this.sortByID(order)
        }
      },
      sortByID(order) {
        if (order === 'ascending') {
          this.listQuery.sort = '+id'
        } else {
          this.listQuery.sort = '-id'
        }
        this.handleFilter()
      },
      resetTemp() {
        this.temp = {
          id: undefined
        }
      },
      // 编辑
      handleUpdate(row) {
        this.temp = Object.assign({}, row) // copy obj
        this.formImgUrl = this.temp.imgUrl
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        // this.dialogFormVisible = true
        this.getCatListOrigin()
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },

      // 获取父类
      getCatListOrigin() {
        getCatListOrigin().then(res => {
          this.dialogFormVisible = false
          this.dialogFormVisible = true
          console.log(res.data)
          this.originList = res.data
        })
      },


      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            console.log(tempData)
            createProCat(tempData).then(() => {
              for (const v of this.list) {
                if (v.id === this.temp.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.temp)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '修改成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
        this.getList()
      },

      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        // this.dialogFormVisible = true
        this.dialogFormVisible = true
        this.getCatListOrigin()
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },

      // 上传图片
      addImg(data) {
        this.dialogLoading = true;
        const formData = new FormData();
        formData.append("file", data.file);
        uploadFile(formData).then(res => {
          console.log(res)
          this.dialogLoading = false;
          this.formImgUrl = res.data.filePath;
        });
      },

      // 添加数据
      createData() {
        this.$refs['dataForm'].validate(valid => {
          if (valid) {
            var formdata = this.temp
            formdata.id = ''
            formdata.isParent = '1'
            formdata.imgUrl = this.formImgUrl
            console.log(formdata)
            createProCat(formdata).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '添加成功',
                type: 'success',
                duration: 2000
              })
              setTimeout(function() { //使用  setTimeout（）方法设定定时1000毫秒
                window.location.reload(); //页面刷新
              }, 1000);
            })
          }
        })
      },


      handledelete(row) {
        // this.rowId=row.broadPic
        this.$confirm('确定删除？ 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
          console.log(row)
          var formdata={
            id:row.id
          }
          deleteProCat(formdata).then(res=>{
            var remove = row.imgUrl
            String.prototype.replaceAll = function(s1, s2) {
              return this.replace(new RegExp(s1, "gm"), s2);
            }
            console.log(remove.replaceAll('/', '*'))
            var newRemove = remove.replaceAll('/', '*')
            deleteFile(newRemove).then(res => {
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.getList()
            })
          })



        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });

      },
      getSortClass: function(key) {
        const sort = this.listQuery.sort
        return sort === `+${key}` ?
          'ascending' :
          sort === `-${key}` ?
          'descending' :
          ''
      },

      statusChange(value) {
        this.temp.status = value
      },
      originNameChange(value) {
        console.log(value)
        this.temp.parentName = value.name
        this.temp.parentId = value.id
      }

    }
  }
</script>
